import materialService, { type PageListReq } from "@/api/services/base/materialService";
import materialTypeService from "@/api/services/base/materialTypeService";
import seriesService from "@/api/services/base/seriesService";
import unitService from "@/api/services/base/unitService";
import TableDictTag from "@/components/grid/TableDictTag";
import { TableToolbar } from "@/components/grid/TableToolbar";
import { Upload } from "@/components/upload";
import useDictionary from "@/hooks/system/useDictionary";
import { t } from "@/locales/i18n";
import { ExportOutlined, UploadOutlined } from "@ant-design/icons";
import { Button, Card, Drawer, Form, Input, Modal, Select, Space, Switch, TreeSelect } from "antd";
import Table, { type ColumnsType } from "antd/es/table";
import type { UploadFile, UploadProps } from "antd/es/upload/interface";
import { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import type { Material } from "./entity";
import { MaterialType } from "../type/entity";
import { ProductSeries } from "../series/entity";
import { Unit } from "../unit/entity";
import { get } from "jquery";

export default function MaterialPage() {
	const [loading, setLoading] = useState(false);
	const [queryParams, setQueryParams] = useState<PageListReq>({
		materialCode: undefined,
		materialName: undefined,
		status: undefined,
		page: 1,
		pageSize: 10,
	});
	const [total, setTotal] = useState(0);
	const [list, setList] = useState<Material[]>([]);
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const [tableSize, setTableSize] = useState<"large" | "middle" | "small">("middle");
	const [drawerVisible, setDrawerVisible] = useState(false);
	const [editingData, setEditingData] = useState<Material | null>(null);
	const [form] = Form.useForm();
	const [isView, setIsView] = useState(true); // 控制表单禁用状态
	const [typeList, setTypeList] = useState<MaterialType[]>([]); // 物料类型列表
	const [seriesList, setSeriesList] = useState<ProductSeries[]>([]); // 产品系列列表
	const [unitList, setUnitList] = useState<Unit[]>([]); // 单位列表

	// 上传相关状态
	const [uploadModalVisible, setUploadModalVisible] = useState(false);
	const [fileList, setFileList] = useState<UploadFile[]>([]);
	const [uploading, setUploading] = useState(false);

	//字典项
	const statusOptions = useDictionary("system_status");

	//动态设置表格高度
	const [tableScrollY, setTableScrollY] = useState(0);
	const PAGE_OFFSET_HEIGHT = 405;
	const updateTableHeight = () => {
		const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
		setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
	};

	useEffect(() => {
		updateTableHeight(); // 初始化
		window.addEventListener("resize", updateTableHeight);
		return () => window.removeEventListener("resize", updateTableHeight);
	}, []);

	useEffect(() => {
		getTypeList();
		getSeriesList();
		getUnitList();
	}, []);

	// 获取产品系列列表
	const getSeriesList = async () => {
		try {
			const data = await seriesService.selectList();
			setSeriesList(data);
		} catch (error) {
			toast.error(`获取产品系列列表失败: ${error.message}`);
		}
	};

	// 获取单位列表
	const getUnitList = async () => {
		try {
			const data = await unitService.selectList();
			setUnitList(data);
		} catch (error) {
			toast.error(`获取单位列表失败: ${error.message}`);
		}
	};

	// 定义表格列
	const columns: ColumnsType<Material> = [
		{
			title: "物料编码",
			width: 150,
			key: "materialCode",
			dataIndex: "materialCode",
		},
		{
			title: "物料名称",
			width: 200,
			key: "materialName",
			dataIndex: "materialName",
		},
		{
			title: "型号规格",
			width: 280,
			key: "spec",
			dataIndex: "spec",
		},
		{
			title: "系列",
			width: 100,
			key: "seriesId",
			dataIndex: "seriesName",
		},
		{
			title: "单位",
			width: 100,
			key: "unitId",
			dataIndex: "unitName",
		},
		{
			title: "类型",
			width: 100,
			key: "typeId",
			dataIndex: "typeName",
		},
		{
			title: "状态",
			width: 100,
			key: "status",
			dataIndex: "status",
			render: (_, record) => <TableDictTag dictCode="system_status" value={record.status} />,
		},
		{
			title: "是否设置安全库存",
			width: 150,
			key: "safeStockFlag",
			dataIndex: "safeStockFlag",
		},
		{
			title: "最低库存量",
			width: 100,
			key: "minStock",
			dataIndex: "minStock",
		},
		{
			title: "最大库存量",
			width: 100,
			key: "maxStock",
			dataIndex: "maxStock",
		},
		{
			title: "描述",
			width: 100,
			key: "description",
			dataIndex: "description",
		},
		{
			title: "操作",
			fixed: "right",
			key: "operation",
			align: "center",
			width: 100,
			render: (_, record) => (
				<Space>
					<Button type="link" onClick={() => handleView(record)}>
						{t("common.view")}
					</Button>
					<Button type="link" onClick={() => handleEdit(record)}>
						{t("common.edit")}
					</Button>
				</Space>
			),
		},
	];

	// 状态管理
	const [selectedValues, setSelectedValues] = useState<string[]>(() =>
		columns.filter((col) => col.key !== "operation").map((col) => String(col.key!)),
	);

	// 处理过滤后的列配置
	const filteredColumns = useMemo(() => {
		return [
			// 显示选中的列
			...columns.filter(
				(col) => selectedValues.includes(String(col.key)) || col.key === "operation", // 始终包含操作列
			),
		].sort((a, b) => {
			// 保持原始顺序
			const originalIndex = columns.findIndex((c) => c.key === a.key);
			const targetIndex = columns.findIndex((c) => c.key === b.key);
			return originalIndex - targetIndex;
		});
	}, [selectedValues]);

	const fetchPageList = () => {
		setLoading(true);
		materialService
			.pageList(queryParams)
			.then((res) => {
				setList(res.records);
				setTotal(res.total);
			})
			.catch((error) => {
				console.log(error);
				toast.error("获取数据失败！", error);
			})
			.finally(() => {
				setLoading(false);
			});
	};

	// 获取物料类型列表
	const getTypeList = () => {
		setLoading(true);
		materialTypeService
			.treeList({
				typeCode: undefined,
				typeName: undefined,
				page: 1,
				pageSize: 100,
			})
			.then((res) => {
				setTypeList(res);
			})
			.catch((error) => {
				console.log(error);
				toast.error("获取数据失败！", error);
			})
			.finally(() => {
				setLoading(false);
			});
	};

	//组件加载时获取组织机构数据
	useEffect(() => {
		fetchPageList();
	}, [queryParams]);

	//触发分页控件
	const handlePageChange = (newPage: number, newPageSize: number) => {
		setQueryParams((prev) => ({
			...prev,
			page: newPage,
			pageSize: newPageSize,
		}));
	};

	const handleEdit = (material: Material) => {
		setEditingData(material);
		form.setFieldsValue(material);
		setDrawerVisible(true);
		setIsView(false);
	};

	/**
	 * 查看物料基础信息
	 * @param material 物料基础信息
	 */
	const handleView = (material: Material) => {
		setEditingData(material);
		form.setFieldsValue(material);
		setIsView(true);
		setDrawerVisible(true);
	};

	const handleSubmit = async (values) => {
		try {
			setLoading(true);
			if (editingData) {
				await materialService.update({ ...values, id: editingData.id });
				toast.success("更新物料基础信息成功");
			} else {
				await materialService.add(values);
				toast.success("创建物料基础信息成功");
			}
			setDrawerVisible(false);
			setEditingData(null);
			form.resetFields();
			fetchPageList();
		} catch (error) {
			toast.error(`${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	const handleDrawerClose = () => {
		setDrawerVisible(false);
		setEditingData(null);
		form.resetFields();
	};

	const handleAdd = () => {
		setEditingData(null);
		form.resetFields();
		setDrawerVisible(true);
		setIsView(false);
	};

	//删除物料基础信息方法
	const handleDelete = async () => {
		try {
			setLoading(true);
			await materialService.remove(selectedRowKeys);
			toast.success("删除物料基础信息成功");
			setSelectedRowKeys([]); // 清空选中项
			fetchPageList(); // 重新加载列表
		} catch (error) {
			toast.error(`删除失败: ${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	// 处理上传按钮点击
	const handleImport = () => {
		setUploadModalVisible(true);
	};

	// 处理上传模态窗关闭
	const handleUploadModalCancel = () => {
		setUploadModalVisible(false);
		setFileList([]);
	};

	//下载上传模板
	const downTemplate = () => {
		materialService
			.downloadTemplate()
			.then((res) => {
				console.log("下载模板");
			})
			.catch((error) => {
				console.error(`下载失败: ${error.message || "未知错误"}`);
				toast.error(`下载失败: ${error.message || "未知错误"}`);
			});
	};

	// 上传前检查
	const beforeUpload = (file: File) => {
		// 这里可以添加文件类型、大小等检查
		const isLt10M = file.size / 1024 / 1024 < 10;
		if (!isLt10M) {
			toast.error("文件必须小于10MB!");
			return false;
		}
		return true;
	};

	// 处理文件列表变化
	const handleFileListChange: UploadProps["onChange"] = ({ fileList: newFileList }) => {
		setFileList(newFileList);
	};

	// 处理文件上传
	const handleFileUpload = async () => {
		if (fileList.length === 0) {
			toast.warning("请选择要上传的文件");
			return;
		}

		setUploading(true);

		console.log("上传文件", fileList);
		// 上传每个文件
		for (const file of fileList) {
			if (file.originFileObj) {
				// 使用修改后的uploadFile方法
				await materialService
					.importData(file.originFileObj)
					.then((res) => {
						toast.success("导入成功");
						setUploadModalVisible(false);
						fetchPageList();
					})
					.catch((error) => {
						toast.error(`上传失败: ${error.message || "未知错误"}`);
					})
					.finally(() => {
						setUploading(false);
					});
			}
		}
	};

	//导出数据
	const handleExport = () => {
		materialService.exportData(queryParams);
	};

	return (
		<>
			{/* 查询条件 */}
			<Card className="mb-4">
				<Form
					layout="inline"
					onFinish={(values) => {
						// 处理查询条件
						setQueryParams((prev) => ({
							...prev,
							...values,
							page: 1,
						}));
					}}
				>
					<Form.Item name="materialCode" label="物料编码">
						<Input placeholder="请输入物料编码" allowClear />
					</Form.Item>
					<Form.Item name="materialName" label="物料名称">
						<Input placeholder="请输入物料名称" allowClear />
					</Form.Item>
					<Form.Item name="status" label="状态">
						<Select options={statusOptions} allowClear style={{ width: 150 }} />
					</Form.Item>
					<Form.Item name="typeId" label="物料类型">
						<TreeSelect
							fieldNames={{
								label: "typeName",
								value: "id",
								children: "children",
							}}
							treeData={typeList}
							style={{ width: 170 }}
							allowClear
						/>
					</Form.Item>
					<Form.Item>
						<Button type="primary" htmlType="submit">
							查询
						</Button>
						<Button
							className="ml-2"
							onClick={() => {
								// 重置查询条件
								setQueryParams({ page: 1, pageSize: 10 });
							}}
						>
							重置
						</Button>
					</Form.Item>
				</Form>
			</Card>
			<div className="h-4" />
			{/* 表格数据 */}
			<Card>
				<div className="flex justify-between mb-4">
					<div className="flex gap-2">
						<Button type="primary" onClick={handleAdd}>
							新增
						</Button>
						<Button danger disabled={selectedRowKeys.length === 0} onClick={handleDelete}>
							删除
						</Button>
						<Button icon={<UploadOutlined />} type="primary" onClick={handleImport}>
							导入
						</Button>
						<Button icon={<ExportOutlined />} type="primary" onClick={handleExport}>
							导出
						</Button>
					</div>
					<TableToolbar
						onRefresh={() => setQueryParams((prev) => ({ ...prev }))}
						onSizeChange={setTableSize}
						columns={columns}
						selectedValues={selectedValues}
						onColumnChange={setSelectedValues}
					/>
				</div>
				<Table
					rowKey="id"
					size={tableSize}
					loading={loading}
					pagination={{
						total,
						current: queryParams.page,
						pageSize: queryParams.pageSize,
						onChange: handlePageChange,
					}}
					columns={filteredColumns}
					dataSource={list}
					rowSelection={{
						type: "checkbox",
						selectedRowKeys: selectedRowKeys,
						onChange: (selectedKeys) => {
							setSelectedRowKeys(selectedKeys as string[]);
						},
					}}
					scroll={{ y: tableScrollY }}
				/>
			</Card>
			{/* 编辑页面 */}
			<Drawer
				title={editingData ? "编辑物料基础信息" : "新增物料基础信息"}
				width={480}
				open={drawerVisible}
				onClose={handleDrawerClose}
				footer={
					<div className="flex justify-end gap-2">
						<Button onClick={handleDrawerClose}>取消</Button>
						{!isView && (
							<Button type="primary" onClick={() => form.submit()}>
								确定
							</Button>
						)}
					</div>
				}
			>
				<Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} onFinish={handleSubmit} disabled={isView}>
					<Form.Item name="materialCode" label="物料编码">
						<Input placeholder="请输入物料编码" />
					</Form.Item>
					<Form.Item name="materialName" label="物料名称">
						<Input placeholder="请输入物料名称" />
					</Form.Item>
					<Form.Item name="spec" label="型号规格">
						<Input placeholder="请输入型号规格" />
					</Form.Item>
					<Form.Item name="seriesId" label="系列">
						<Select
							placeholder="请选择系列"
							options={seriesList.map((item) => ({
								label: item.name,
								value: item.id,
							}))}
							allowClear
						/>
					</Form.Item>
					<Form.Item name="unitId" label="单位">
						<Select
							placeholder="请选择单位"
							options={unitList.map((item) => ({
								label: item.unitName,
								value: item.id,
							}))}
							allowClear
						/>
					</Form.Item>
					<Form.Item name="typeId" label="类型">
						<TreeSelect
							fieldNames={{
								label: "typeName",
								value: "id",
								children: "children",
							}}
							treeData={typeList}
							allowClear
						/>
					</Form.Item>
					<Form.Item name="status" label="状态">
						<Select options={statusOptions} />
					</Form.Item>
					<Form.Item
						name="safeStockFlag"
						label="是否设置安全库存"
						valuePropName="checked"
						normalize={(value) => value === 1}
						getValueFromEvent={(checked) => (checked ? 1 : 0)}
					>
						<Switch checkedChildren="是" unCheckedChildren="否" disabled={isView} />
					</Form.Item>
					<Form.Item name="minStock" label="最低库存量">
						<Input placeholder="请输入最低库存量" />
					</Form.Item>
					<Form.Item name="maxStock" label="最大库存量">
						<Input placeholder="请输入最大库存量" />
					</Form.Item>
					<Form.Item name="description" label="描述">
						<Input placeholder="请输入描述" />
					</Form.Item>
				</Form>
			</Drawer>

			{/* 上传文件模态窗 */}
			<Modal
				title="上传文件"
				open={uploadModalVisible}
				confirmLoading={uploading}
				onCancel={handleUploadModalCancel}
				footer={[
					<Button key="cancel" onClick={handleUploadModalCancel}>
						取消
					</Button>,
					<Button key="upload" type="primary" loading={uploading} onClick={handleFileUpload}>
						上传
					</Button>,
				]}
			>
				<Upload
					beforeUpload={beforeUpload}
					onChange={handleFileListChange}
					fileList={fileList}
					multiple={false}
					thumbnail={false}
				/>
				<div className="mt-4 text-gray-500">
					单个文件大小不超过10MB
					<Button color="primary" variant="link" onClick={downTemplate}>
						下载模板
					</Button>
					仅允许导入xls、xlsx格式文件。
				</div>
			</Modal>
		</>
	);
}
